package com.sc.sc250601.cook.controller;

import com.sc.sc250601.cook.pojo.Like;
import com.sc.sc250601.cook.pojo.Post;
import com.sc.sc250601.cook.pojo.Result;
import com.sc.sc250601.cook.service.PostService;
import com.sc.sc250601.cook.util.UpDowns;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/post")
public class PostController {
    @Autowired
    PostService ps;

    @RequestMapping("/selectAll")
    public Result selectAll(){
        List<Post> posts=ps.selectAll();
        return  new Result(1,"查询成功",posts);
    }

    //通过帖子id查找单个
    @RequestMapping("/selectById")
    public Result selectById(Long id){
        //查询的同时浏览量+1
        Post p=ps.selectById(id);
        if(p!=null){
            return new Result(1,"查询成功",p);
        }
        return new Result(0,"查询失败");
    }

    @RequestMapping("/selectByUid")
    public Result selectByUid(@RequestBody List<Long> uids){
        List<Post> posts=ps.selectByUid(uids);
        if(posts!=null){
            return  new Result(1,"查询成功",posts);
        }
        return  new Result(0,"暂无动态");
    }
    @RequestMapping("/addLikeCount")
    public Result handleLikeOperation(@RequestBody Like like) {
        // 调用服务层处理点赞逻辑
        Result result = ps.addLikeCount(like);
        // 即使result为null也返回统一格式的失败结果
        return result != null ? result : new Result(0, "点赞操作失败");
    }
    @RequestMapping("/addPost")
    public Result addPost(Post p, MultipartFile[] myHeads){
        StringBuilder s=new StringBuilder();
       for(int i=0;i<myHeads.length;i++){
           s.append("/api/upload/"+UpDowns.upload(myHeads[i]));
           if(i!=myHeads.length-1)s.append(",");
       }
       p.setImages(s.toString());
        int n=ps.addPost(p);
        if(n>0){
            return new Result(1,"新增帖子成功");
        }
        return new Result(0,"新增帖子失败");
    }


}
